<template>

	<view class="content">
		<view style="width: 100%; background-color: #fff; height: 88rpx;"></view>
		<view style="width: 100%; height: 88rpx;margin-bottom: 16rpx; background-color: #fff;">
			<view class="top">
				<image src="../../static/img/back.png" mode="widthFix" @tap="back"></image>
				<view class="topText">{{fname}}</view>
				<view></view>
			</view>
		</view>
		<!-- 聊天内容 -->
		<scroll-view class="chat" scroll-y="true" :scroll-with-animation="swanition" :scroll-into-view="scrollToView"
			@scrolltoupper="nextpage">
			<!-- <view class="loading" :class="{displaynone:isloading}">
				<image src="../../static/img/loading.png" class="loading-img" :animation="animationData"
					mode="widthFix"></image>
			</view> -->
			<view class="chat-main" :style="{paddingBottom:inputh+'px'}">
				<view class="chat-ls" v-for="(item,index) in unshiftmsg" :key="index" :id="'msg'+ index">
					<view class="chat-time" v-if="item.time != ''">{{changeTime(item.time)}}</view>
					<view class="msg-m msg-left" v-if="item.user_id ==  fid">
						<image class="user-img" :src="fidImg"></image>
						<view class="message" v-if="item.type == 0">
							<!-- 文字 -->
							<view class="msg-text"> {{item.message}}</view>

						</view>
						<view class="message" v-if="item.type == 1" @tap="previewImg(item.message)">
							<!-- 图像 -->
							<image :src="item.message" class="msg-img" mode="widthFix"></image>
						</view>
						<view class="message" v-if="item.type == 2" @tap="playVoice(item.message.voice)">
							<!-- 音频 -->
							<view class="msg-text voice" :style="{width:item.message.time*4+'rpx'}">
								<image src="../../static/chatAction/saying.png" class="voice-img"></image>
								{{item.message.time}}″
							</view>
						</view>
						<view class="message" v-if="item.type == 3" @tap="openLocation(item.message)">
							<!-- 位置 -->
							<view class="msg-map">
								<view class="map-name">{{item.message.name}}</view>
								<view class="map-address">{{item.message.address}}</view>
								<!-- 如果map不起作用，就可以直接用一张图片去替代 -->
								<map class="map" :longitude="item.message.longitude" :latitude="item.message.latitude"
									:markers="covers(item.message)"></map>
							</view>
						</view>
					</view>
					<view class="msg-m msg-right" v-if="item.user_id != fid">
						<image class="user-img" :src="userImg"></image>
						<view class="message" v-if="item.type == 0">
							<view class="msg-text">{{item.message}}</view>
						</view>
						<view class="message" v-if="item.type == 1" @tap="previewImg(item.message)">
							<image :src="item.message" class="msg-img" mode="widthFix"></image>
						</view>
						<view class="message" v-if="item.type == 2" @tap="playVoice(item.message.voice)">
							<!-- 音频 -->
							<view class="msg-text voice" :style="{width:item.message.time*4+'rpx'}">
								{{item.message.time}}″
								<image src="../../static/chatAction/saying.png" class="voice-img"></image>
							</view>
						</view>
						<view class="message" v-if="item.type == 3" @tap="openLocation(item.message)">
							<!-- 位置 -->
							<view class="msg-map">
								<view class="map-name">{{item.message.name}}</view>
								<view class="map-address">{{item.message.address}}</view>
								<map class="map" :longitude="item.message.longitude" :latitude="item.message.latitude"
									:markers="covers(item.message)"></map>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<submit @inputs="inputs" @heights="heights"></submit>
	</view>
</template>

<script>
	import myfun from "@/common/dateTime.js";
	import submit from "../../components/submit/submit.vue";

	//音频播放
	// const innerAudioContext = 

	export default {
		data() {
			return {

				innerAudioContext: {},
				msg: [{
						"sendName": "xpq",
						"receviceName": "゛时光い",
						"message": {
							"address": "广东邮电职业技术学院",
							"longitude": 113.364363,
							"latitude": 23.134546,
							"name": "中山大道西191号",
						},
						"time": "2022-01-06 12:40:12",
						"type": 3
					}, {
						"sendName": "゛时光い",
						"receviceName": "xpq",
						"message": {
							"voice": "时光匆匆流过",
							"time": 2 //秒
						},
						"time": "2022-01-06 12:22:12",
						"type": 2
					}, {
						"sendName": "xpq",
						"receviceName": "゛时光い",
						"message": {
							"voice": "谢谢你",
							"time": 60 //秒
						},
						"time": "2022-01-06 12:00:12",
						"type": 2
					}, {
						"sendName": "゛时光い",
						"receviceName": "xpq",
						"message": "这是第九条未读消息",
						"time": "2022-01-03 12:22:12",
						"type": 0
					},
					{
						"sendName": "゛时光い",
						"receviceName": "xpq",
						"message": "这是第八条未读消息",
						"time": "2022-01-02 12:22:07",
						"type": 0
					},
					{
						"sendName": "xpq",
						"receviceName": "xpq",
						"message": "这是第七条未读消息",
						"time": "2021-12-19 12:22:03",
						"type": 0
					},
					{
						"sendName": "゛时光い",
						"receviceName": "xpq",
						"message": "这是第六条未读消息",
						"time": "2021-12-19 12:21:58",
						"type": 0
					},
					{
						"sendName": "゛时光い",
						"receviceName": "xpq",
						"message": "http://demo.rageframe.com/attachment/images/2021/11/18/image_1637224530_diIlZlmm.jpeg",
						"time": "2021-12-19 12:21:54",
						"type": 1
					},
					{
						"sendName": "xpq",
						"receviceName": "゛时光い",
						"message": "http://demo2.rageframe.com/attachment/images/2021/09/01/image_1630483477_N03W37zs.jpg",
						"time": "2021-12-19 12:21:48",
						"type": 1
					},
					{
						"sendName": "゛时光い",
						"receviceName": "xpq",
						"message": "这是第三条未读消息",
						"time": "2021-12-19 12:21:42",
						"type": 0
					},
					{
						"sendName": "゛时光い",
						"receviceName": "xpq",
						"message": "这是第二条未读消息",
						"time": "2021-12-19 12:21:33",
						"type": 0
					},
					{
						"sendName": "゛时光い",
						"receviceName": "xpq",
						"message": "http://demo2.rageframe.com/attachment/images/2021/09/01/image_1630483477_N03W37zs.jpg",
						"time": "2021-12-19 11:02:18",
						"type": 1
					},
					{
						"sendName": "゛时光い",
						"receviceName": "xpq",
						"message": "爱你啊",
						"time": "2021-12-18 20:37:03",
						"type": 0
					}
				],
				// 反转数据接收
				unshiftmsg: [],
				imgMsg: [],
				scrollToView: '',
				oldTime: new Date(),
				inputh: '60',
				animationData: {},
				loading: '',
				isloading: true,
				swanition: true,
				userId: 0,
				fid: 0,
				fidImg: '',
				userImg: '',
				fname: '',
				nowPage: 0
			}
		},
		onShow() {
			this.getUserImg()
			// this.receivewSocketMsg()
			// 数组倒叙 主要是应对后端传过来的数据

		},
		onLoad(e) {
			this.fid = e.fid
			this.fidImg = e.img
			this.fname = e.name
			// this.nextpage();
			
			this.receivewSocketMsg()
			this.getMsg();
		},
		components: {
			submit,
		},
		methods: {
			async getMsg() {
				this.swanition = false
				await uni.request({
					url: 'http://localhost:3000/chat/msg',
					method: "GET",
					data: {
						friendId: this.fid,
						userId: this.userId,
						// nowPage: 0,
						// pageSize: 10
					},
					success: res => {
						if (res.data.code == 200) {
							this.msg = res.data.data.map(item => {
								if (item.type == 1 || item.type == 2) {
									item.message = "http://localhost:3000" + item.message
								}
								return item
							})
							console.log(this.msg)
						}
						for (var i = 0; i < this.msg.length; i++) {
							//时间间隔处理
							if (i < this.msg.length - 1) { //这里表示头部时间还是显示一下
								let t = myfun.spaceTime(this.oldTime, this.msg[i].time);
								if (t) {
									this.oldTime = t;
								}
								this.msg[i].time = t;
							}
							// 获取图片，为下面的预览做准备
							if (this.msg[i].type == 1) {
								this.imgMsg.unshift(this.msg[i].message)
							}
							this.unshiftmsg.unshift(this.msg[i]);
						}
						console.log(this.unshiftmsg)
					}
				})
				this.swanition = true
				// 跳转到最后一条数据 与前面的:id进行对照
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.unshiftmsg.length - 1)
				})
			},
			//获取用户头像
			getUserImg() {
				uni.getStorage({
					key: 'userId',
					success: res => {
						//获取存储的用户信息
						let data = JSON.parse(res.data)
						this.userId = data.userId
						if (data.avatar) {
							this.userImg = "http://localhost:3000/upload/" + data.avatar
						}

					},

				});
			},
			// loading动画
			nextpage() {
				this.isloading = false;
				var animation = uni.createAnimation({
					duration: 1000,
					timingFunction: 'step-start',
				})
				this.animation = animation
				let i = 1
				let loading = setInterval(function() {
					animation.rotate(i * 30).step()
					this.animationData = animation.export()
					i++;

				}.bind(this), 1000)
			},
			// 返回
			back() {
				uni.switchTab({
					url: '/pages/chat/chat'
				})
			},
			changeTime(date) {
				return myfun.dateTime1(date);
			},
			// 进行图片的预览
			previewImg(e) {
				let index = 0;
				for (let i = 0; i < this.imgMsg.length; i++) {
					if (this.imgMsg[i] == e) {
						index = i;
					}
				}
				// console.log("index", index)
				// 预览图片
				uni.previewImage({
					current: index,
					urls: this.imgMsg,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data
								.index +
								1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			//音频播放
			playVoice(e) {
				// const innerAudioContext = uni.createInnerAudioContext();
				let innerAudioContext = this.innerAudioContext;
				// 上面定义了是可以的,但是vue不知道你改变

				innerAudioContext.autoplay = true;
				innerAudioContext.src = e;
				console.log(e)
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
					console.log(res)
				});
			},
			//地图定位
			covers(e) {
				let map = [{
					// id:1,
					// iconPath:'../../static/img/loacation.png',
					latitude: e.latitude,
					longitude: e.longitude,
					width: 16,
					height: 16,
				}]
				return (map);
			},
			//跳转地图信息
			openLocation(e) {
				uni.openLocation({
					latitude: e.latitude,
					longitude: e.longitude,
					name: e.name,
					address: e.address,
					success: function() {
						console.log('success');
					}
				});
			},
			//接受输入内容
			inputs(e) {
				this.swanition = true
				//时间间隔处理
				let data = {
					friend_id: this.fid,
					user_id: this.userId,
					message: e.message,
					time: new Date(),
					type: e.type
				};
				// console.log(e)
				// 发送给服务器消息
				// onSendWS(JSON.stringify(data));

				this.unshiftmsg.push(data);
				// 跳转到最后一条数据 与前面的:id进行对照
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.unshiftmsg.length - 1)
				})

				// socket提交
				if (e.type == 0 || e.type == 3) {
					//发送给后端
					this.sendSocket(e)
				}
				if (e.type == 1) {
					this.imgMsg.push(e.message);

					let url = myfun.fileName(new Date)
					const uploadTask = uni.uploadFile({
						url: 'http://localhost:3000/file/upload', //仅为示例，非真实的接口地址
						filePath: e.message,
						name: 'file',
						formData: {
							url: url,
							name: new Date().getTime() + 'id' + Math.ceil(Math.random() * 10)
						},
						success: (uploadFileRes) => {
							let data = {
								message: uploadFileRes.data,
								type: 1,
							}
							this.sendSocket(data)
						}


					});
				}
				if (e.type == 2) {
					//提交音频
					let url = myfun.fileName(new Date())
					const uploadTask = uni.uploadFile({
						url: 'http://localhost:3000/file/upload', //仅为示例，非真实的接口地址
						filePath: e.message.voice,
						name: 'file',
						formData: {
							url: url,
							name: new Date().getTime() + 'id' + Math.ceil(Math.random() * 10)
						},
						success: (uploadFileRes) => {
							let data = {
								message: uploadFileRes,
								type: e.type,
							}
							this.sendSocket(data)
						}
					});
				}

			},
			// 发送数据
			sendSocket(e) {
				this.socket.emit('msg', e, this.userId, this.fid)
			},
			// 接收数据
			receivewSocketMsg() {
				this.socket.on('msg', (msg, fromId) => {
					// let len = this.msg.length;
					// console.log(msg)
					// let nowTime = new Date();
					// let t = myfun.spaceTime(this.oldTime, this.msg[i].time);
					// if (t) {
					// 	this.oldTime = t;
					// }
					// nowTime = t;
					if (msg.type == 1 || msg.type == 2) {
						msg.message = "http://localhost:3000" + msg.message
						console.log(msg.message)
					}
					let data = {
						friend_id: this.userId,
						user_id: this.fid,
						message: msg.message,
						time: new Date(),
						type: msg.type
					};


					this.unshiftmsg.push(data);
					if (msg.type == 1) {
						this.imgMsg.push(msg.message)
					}
					// 跳转到最后一条数据 与前面的:id进行对照
					this.$nextTick(function() {
						this.scrollToView = 'msg' + (this.unshiftmsg.length - 1)
					})
					
					this.swanition = true;
				})

				
			},
			//输入框高度
			heights(e) {
				// console.log("高度:", e)
				this.inputh = e;
				this.goBottom();
			},
			// 滚动到底部
			goBottom() {
				this.swanition = true
				this.scrollToView = '';
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.unshiftmsg.length - 1)
				})
			},

		},
		mounted() {
			this.innerAudioContext = uni.createInnerAudioContext();
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
	}

	.content {
		height: 100%;
		background-color: rgba(244, 244, 244, 1);
	}

	.top {
		background-color: #fff;
		display: flex;
		position: fixed;
		z-index: 1000;
		top: 84rpx;
		left: 0rpx;
		width: 100%;
		height: 88rpx;
		font-weight: bold;
		font-size: 32rpx;
		line-height: 88rpx;
		overflow: auto;
		justify-content: space-between;
		align-items: center;

		image {
			width: 52rpx;
			margin-left: 18rpx;
			background-color: #fff
		}

		.topText {
			margin-left: -64rpx;
		}
	}

	.displaynone {
		display: none;
	}

	.chat {
		height: 100%;

		.loading {
			text-align: center;

			.loading-img {
				width: 60rpx;
			}
		}

		.chat-main {
			padding-left: 32rpx;
			padding-right: 32rpx;
			padding-top: 20rpx;
			// padding-bottom: 120rpx;  //获取动态高度
			display: flex;
			flex-direction: column;
		}

		.chat-ls {
			.chat-time {
				font-size: 24rpx;
				color: rgba(39, 40, 50, 0.3);
				line-height: 34rpx;
				padding: 10rpx 0rpx;
				text-align: center;
			}

			.msg-m {
				display: flex;
				padding: 20rpx 0;

				.user-img {
					flex: none;
					width: 80rpx;
					height: 80rpx;
					border-radius: 20rpx;
				}

				.message {
					flex: none;
					max-width: 480rpx;
				}

				.msg-text {
					font-size: 32rpx;
					color: rgba(39, 40, 50, 1);
					line-height: 44rpx;
					padding: 18rpx 24rpx;
				}

				.msg-img {
					max-width: 400rpx;
					border-radius: 20rpx;
				}

				.msg-map {
					background: #fff;
					width: 464rpx;
					height: 284rpx;
					overflow: hidden;

					.map-name {
						font-size: 32rpx;
						color: rgba(39, 40, 50, 1);
						line-height: 44rpx;
						padding: 18rpx 24rpx 0 24rpx;
						//下面四行是单行文字的样式
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 1;
						overflow: hidden;
					}

					.map-address {
						font-size: 24rpx;
						color: rgba(39, 40, 50, 0.4);
						padding: 0 24rpx;
						//下面四行是单行文字的样式
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 1;
						overflow: hidden;
					}

					.map {
						padding-top: 8rpx;
						width: 464rpx;
						height: 190rpx;
					}
				}

				.voice {
					// width: 200rpx;
					min-width: 100rpx;
					max-width: 400rpx;
				}

				.voice-img {
					width: 28rpx;
					height: 36rpx;

				}
			}

			.msg-left {
				flex-direction: row;

				.msg-text {
					margin-left: 16rpx;
					background-color: #fff;
					border-radius: 0rpx 20rpx 20rpx 20rpx;
				}

				.ms-img {
					margin-left: 16rpx;
				}

				.msh-map {
					margin-left: 16rpx;
					border-radius: 0rpx 20rpx 20rpx 20rpx;
				}

				.voice {
					text-align: right;

				}

				.voice-img {
					float: left;
					width: 28rpx;
					height: 36rpx;
					padding-bottom: 4rpx;
				}
			}

			.msg-right {
				flex-direction: row-reverse;

				.msg-text {
					margin-right: 16rpx;
					background-color: rgba(184, 134, 248, 0.33);
					border-radius: 20rpx 0rpx 20rpx 20rpx;
				}

				.ms-img {
					margin-right: 16rpx;
				}

				.msh-map {
					margin-left: 16rpx;
					border-radius: 20rpx 0rpx 20rpx 20rpx;
				}

				.voice {
					text-align: left;

				}

				.voice-img {
					float: right;
					padding: 4rpx;
					width: 28rpx;
					height: 36rpx;
					transform: rotate(180deg);
				}
			}
		}
	}
</style>
